package com.group01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group01.dto.Order.OrderDTO;
import com.group01.dto.Order.OrderDeliveryDTO;
import com.group01.dto.Order.OrderItemDTO;
import com.group01.enums.CodeAndMessageEnum;
import com.group01.mapper.OrderItemMapper;
import com.group01.pojo.Order;
import com.group01.pojo.OrderItem;
import com.group01.result.OrderPageTemplate;
import com.group01.result.Result;
import com.group01.service.OrderService;
import com.group01.mapper.OrderMapper;
import com.group01.utils.BeanCopyUtils;
import com.group01.utils.CommonUtils;
import com.group01.vo.Order.OrderGetInfoVO;
import com.group01.vo.Order.OrderGetPageVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
* @author 19559
* @description 针对表【es_order(订单表)】的数据库操作Service实现
* @createDate 2024-06-22 12:11:46
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService{

    private final OrderMapper orderMapper;

    private final OrderItemMapper orderItemMapper;

    public OrderServiceImpl(OrderMapper orderMapper, OrderItemMapper orderItemMapper) {
        this.orderMapper = orderMapper;
        this.orderItemMapper = orderItemMapper;
    }

    /**
     * 分页 + 条件查询订单信息
     * @param pageNum 页码
     * @param pageSize 每页显示条数
     * @param id 订单编号
     * @param status 订单状态
     * @return {@link OrderPageTemplate }<{@link OrderGetPageVO }>
     */
    @Override
    public OrderPageTemplate<OrderGetPageVO> getOrderList(Integer pageNum, Integer pageSize, String id, Integer status) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(StringUtils.hasText(id), "o.id", id)
                .eq(status != null, "o.status", status);

        // 分页查询
        Page<Order> page = new Page<>(pageNum, pageSize);
        orderMapper.getOrderPageInfo(page, queryWrapper);
        // Bean拷贝
        List<OrderGetPageVO> vos = BeanCopyUtils.copyBeanList(page.getRecords(), OrderGetPageVO.class);
        return new OrderPageTemplate<>(page.getTotal(), vos);
    }

    /**
     * 根据订单编号查询订单信息
     * @param orderId 订单编号
     * @return {@link OrderGetInfoVO }
     */
    @Override
    public OrderGetInfoVO getOrderInfoById(String orderId) {

        // 先查询出订单项目
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("o.id", orderId);

        OrderGetInfoVO orderGetInfoVO = orderMapper.getOrderGetInfoById(queryWrapper);

        // 再查询出商品子项
        QueryWrapper<OrderItem> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("a.order_id", orderId);

        // 赋值
        orderGetInfoVO.setOrderItems(orderItemMapper.selectOrderItemAndProductByOrderId(queryWrapper1));

        // 返回
        return orderGetInfoVO;
    }

    /**
     * 填写发货信息
     * @param orderDeliveryDTO 订单配送信息DTO
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> deliveryOrderInfo(OrderDeliveryDTO orderDeliveryDTO) {

        Long count = orderMapper.selectCount(new LambdaQueryWrapper<Order>().eq(Order::getUserId, orderDeliveryDTO.getOrderId()));

        if (count != 0) {
            return Result.error(CodeAndMessageEnum.FIND_ORDER_ID_FAIL);
        }

        // Bean拷贝
        Order order = BeanCopyUtils.copyBean(orderDeliveryDTO, Order.class);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        return Result.success(CodeAndMessageEnum.SUCCESS_ADD_DELIVERY);
    }

    /**
     * 获取用户的订单列表
     * @param id 订单编号
     * @param status 订单状态
     * @return {@link Result }<{@link OrderGetInfoVO }>
     */
    @Override
    public Result<List<OrderGetPageVO>> getOrderInfos(String id, Integer status) {

        /*
         * 获取当前用户id
         */
        Integer userId = CommonUtils.getLocalId();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("o.user_id", userId)
                .eq(StringUtils.hasText(id), "o.id", id)
                .eq(status != null, "o.status", status);

        // Bean拷贝
        List<OrderGetPageVO> vos = BeanCopyUtils.copyBeanList(orderMapper.getOrderListInfo(queryWrapper) , OrderGetPageVO.class);
        return Result.success(CodeAndMessageEnum.FIND_RESULT, vos);
    }

    /**
     * 新增订单
     * @param orderDTO 订单信息DTO
     * @return {@link Result }<{@link String }>
     */
    @Transactional
    @Override
    public Result<OrderGetPageVO> addOrder(OrderDTO orderDTO) {
        /*
         * 构造编号
         */
        String uuid = "final" + CommonUtils.getUUID();
        List<OrderItemDTO> list = orderDTO.getOrderItemCreateDTO();

        /*
         * 获取用户id
         */
        Integer userId = CommonUtils.getLocalId();

        /*
         * 新增订单
         */
        Integer count = orderMapper.addOrderInfo(uuid, orderDTO, userId);
        if(count == 0) {
            return Result.error(CodeAndMessageEnum.ADD_ORDER_FAIL, null);
        }

        /*
         * 新增订单项
         */
        count = orderItemMapper.batchInsertOrderItem(uuid, list);
        if(count != list.size()) {
            return Result.error(CodeAndMessageEnum.ADD_ORDER_ITEM_FAIL, null);
        }

        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("o.id" , uuid);

        // Bean拷贝
        OrderGetPageVO vo = BeanCopyUtils.copyBean(orderMapper.getOrderListInfo(queryWrapper).get(0) , OrderGetPageVO.class);
        return Result.success(CodeAndMessageEnum.SUCCESS_ADD_ORDER, vo);
    }

    /**
     * 确认收货
     * @param orderId 订单id
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> completeOrder(String orderId) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getId , orderId);

        Long count = orderMapper.selectCount(queryWrapper);
        if(count == 0) {
            return Result.error(CodeAndMessageEnum.ORDER_NOT_EXIST);
        }

        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper
                .set(Order::getStatus , 4)
                .eq(Order::getId , orderId);

        orderMapper.update(updateWrapper);
        return Result.success(CodeAndMessageEnum.SUCCESS_COMPLETE_ORDER, null);
    }

    /**
     * 关闭订单
     * @param orderId 订单id
     * @return {@link Result }<{@link String }>
     */
    @Override
    public Result<String> closeOrder(String orderId) {
        Order order = orderMapper.selectById(orderId);
        if(order == null) {
            return Result.error(CodeAndMessageEnum.ORDER_NOT_EXIST);
        }

        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();

        updateWrapper
                .set(Order::getStatus , 5)
                .eq(Order::getId , orderId);

        orderMapper.update(updateWrapper);

        return Result.success(CodeAndMessageEnum.SUCCESS_CLOSE_ORDER, null);
    }

    /**
     * 支付成功更新订单信息
     * @param order 订单信息
     */
    @Override
    public void updateOrderById(Order order) {
        LambdaUpdateWrapper<Order> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(Order::getId , order.getId())
                .set(Order::getStatus, order.getStatus())
                .set(Order::getTrackingNumber, order.getTrackingNumber())
                .set(Order::getPayWay, order.getPayWay())
                .set(Order::getPayDate, order.getPayDate());
        orderMapper.update(order , queryWrapper);
    }
}




